package com.golxen.framework.netty.websocket.codec;


import com.golxen.framework.PBPacket.PBPacket;
import com.golxen.utils.LogUtil;
import com.mysql.cj.util.LogUtils;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageEncoder;
import io.netty.handler.codec.http.websocketx.WebSocketFrameEncoder;
import org.slf4j.Logger;

import java.util.ArrayList;
import java.util.List;

public class AgentWebSocketEncoder extends MessageToMessageEncoder<PBPacket> implements WebSocketFrameEncoder {

    private static Logger logger = LogUtil.COMMON;

    public AgentWebSocketEncoder() {

    }

    //加了我们的PBPacket编码
    @Override
    protected void encode(ChannelHandlerContext ctx, PBPacket msg, List<Object> out) throws Exception {
        if (msg.getMyMsg() instanceof ArrayList) {
            ArrayList<PBPacket> messageBuffer = (ArrayList<PBPacket>)msg.getMyMsg();
            for (PBPacket message : messageBuffer) {
                encode0(ctx, message, out);
            }
        } else {
            encode0(ctx, msg, out);
        }
    }

    private void encode0(ChannelHandlerContext ctx, PBPacket msg, List<Object> out) throws Exception {
        int dataSize = PBPacket.HDR_SIZE;
        if (msg.getBytes() != null) {
            dataSize += msg.getBytes().length;
        }

        boolean release = true;
        ByteBuf buf = null;
        try {
            if (dataSize <= 125) {
                int size = 2 + dataSize;
                buf = ctx.alloc().buffer(size);
                buf.writeByte(130);
                byte b = (byte) (dataSize);
                buf.writeByte(b);
                //加了这个，写入我们的PBPacket编码
                msg.writeHeaderByte(dataSize, buf);
            } else if (dataSize <= 0xFFFF) {
                int size = 4 + dataSize;
                buf = ctx.alloc().buffer(size);
                buf.writeByte(130);
                buf.writeByte(126);
                buf.writeByte(dataSize >>> 8 & 0xFF);
                buf.writeByte(dataSize & 0xFF);
                //
                msg.writeHeaderByte(dataSize, buf);
            } else {
                // 处理包过大
                logger.warn("max size of code = " + msg.getCode() + " length = " + dataSize);
                int size = 10 + dataSize;
                buf = ctx.alloc().buffer(size);
                buf.writeByte(130);
                buf.writeByte(127);
                buf.writeLong(dataSize);
                //
                msg.writeHeaderByte(dataSize, buf);
            }

            out.add(buf);

            release = false;
        } catch (Exception e) {
            logger.error("", e);
        } finally {
            if (release && buf != null) {
                buf.release();
            }
        }
    }

}
